﻿using System;
using System.Collections.Generic;
using System.Text;
using NAnt.Core;
using NAnt.Core.Functions;
using NAnt.Core.Attributes;
using System.Globalization;
using System.Threading;

namespace NAntExt.Functions
{
    [FunctionSet("parallel", "Threading")]
    public class ParallelFunctions : FunctionSetBase
    {
        public static TDictionary<Thread, TDictionary<string, string>> ParallelProperties = new TDictionary<Thread, TDictionary<string, string>>();

        #region Public Instance Constructors

        public ParallelFunctions(Project project, PropertyDictionary properties)
            : base(project, properties)
        {
        }

        #endregion Public Instance Constructors

        #region Public Static Methods

        [Function("get-property-value")]
        public static string GetThreadPropertyValue(string name)
        {
            return GetThreadPropertyValue(Thread.CurrentThread, name);
        }

        public static string GetThreadPropertyValue(Thread thread, string name)
        {
            if (ParallelProperties.ContainsKey(thread))
            {
                TDictionary<string, string> threadProperties = ParallelProperties[thread];
                if (threadProperties.ContainsKey(name))
                {
                    return threadProperties[name];
                }
            }
            throw new ArgumentOutOfRangeException("The property does not exist in this thread.", name, "name");
        }

        [Function("set-property-value")]
        public static string SetThreadPropertyValue(string name, string value)
        {
            SetThreadPropertyValue(Thread.CurrentThread, name, value);
            return string.Empty;
        }

        public static void SetThreadPropertyValue(Thread thread, string name, string value)
        {
            TDictionary<string, string> threadProperties;
            if (ParallelProperties.ContainsKey(thread))
            {
                threadProperties = ParallelProperties[thread];
            }
            else
            {
                lock (ParallelProperties)
                {
                    threadProperties = new TDictionary<string, string>();
                    ParallelProperties.Add(thread, threadProperties);
                }
            }

            if (threadProperties.ContainsKey(name))
            {
                threadProperties[name] = value;
            }
            else
            {
                threadProperties.Add(name, value);
            }
        }

        #endregion Public Static Methods
    }
}